package com.k2data.k2de.utils;

import com.k2data.k2de.client.KafkaClient;
import k2platform.common.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;

public class InitClientForEx {

    private static final Logger LOGGER = LoggerFactory.getLogger(InitClientForEx.class);

    // 异常topic的kafka client.
    private static KafkaClient clientForEx;

    public static KafkaClient initClientForEx(String platformServer) {
        try {
            clientForEx = new KafkaClient(Constants.KAFKA_TOPIC_NAME_EXCEPTION, platformServer);
        } catch (ExecutionException e) {
            LOGGER.error("kafka producer can't send message to server: " + platformServer);
            e.printStackTrace();
            System.exit(-1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return clientForEx;
    }

    /**
     * send MessageToExceptionRegion
     *
     * @param msg         abnormal message
     * @param clientForEx KafkaClient for abnormal message
     */
    public static void sendMessageToExceptionRegion(String msg, KafkaClient clientForEx, String key) {
        try {
            clientForEx.sendMessageSync(key + RandomNumber.getRandomNum(), msg);
            LOGGER.info("Send exception message success.");
        } catch (ExecutionException | InterruptedException e1) {
            LOGGER.warn("Send exception record to kafka server failed. Error message is: {}"
                    , e1.getMessage());
        }
    }
}
